package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.common.config.CodeConfig;
import com.campus.entity.BuildingEntity;
import com.campus.entity.Info;
import com.campus.entity.ResultBody;
import com.campus.entity.System.SysUser;
import com.campus.entity.Teacher;
import com.campus.mapper.*;
import com.campus.service.AccountMapOpenidService;
import com.campus.service.InfoService;
import com.campus.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: AlaskaBoo
 * @Date: 2022-11-02 19:34
 **/
@RestController
@RequestMapping("/api/info")
@Slf4j
public class InfoController {
    @Autowired
    private InfoService infoService;
    @Autowired
    private UploadService uploadService;
    @Value("${qiniu.prefix}")
    private String prefix;

    @Autowired
    private WeChatController weChatController;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 新增信息
     *
     * @param info
     * @return
     */
    @PostMapping
    @CacheEvict(value="info", allEntries =true)
    public ResultBody saveInfo(Info info, MultipartFile multipartFile,String account) {
        if (multipartFile != null) {
            //获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf + 1);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String uuid = UUID.randomUUID().toString();
            String fileName = uuid + "." + suffix;
            String imgSrc = prefix + "/" + fileName;
            try {
                info.setImgSrc(imgSrc);
                info.setCreateTime(new Date());
                infoService.saveOrUpdate(info);
                uploadService.upload2Qiniu(multipartFile.getBytes(), fileName);
            } catch (Exception e) {
                e.printStackTrace();
                //图片上传失败
                return ResultBody.error().message(CodeConfig.PIC_UPLOAD_FAIL.message);
            }
        }
        info.setCreateTime(new Date());
        info.setCreateBy(account);
        infoService.saveOrUpdate(info);



        Map<String,String> infos = new HashMap<>();

        infos.put("thing6",info.getPublishTag());
        System.err.println(info.getCreateTime());
        infos.put("time5", patternTime(info.getCreateTime()));
        infos.put("thing8",info.getPublishTitle());
        infos.put("thing7",info.getDeadline());

        if (buildingMapper.selectCount(new QueryWrapper<BuildingEntity>().eq("building_admin",account))!=0){
            weChatController.sendFromDormAdmin(account,infos,"");
        }else{
            if(teacherMapper.selectCount(new QueryWrapper<Teacher>().eq("account",account))!=0){
                weChatController.sendFromInstructor(account,infos,"");
            }else{
                SysUser account1 = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("account", account));
                if (account1.getUserType().equals(String.valueOf(5))){
                    weChatController.sendFromCommittee(account,infos,"");
                }else{
                    weChatController.sendToPerson(account,infos,"");
                }
            }
        }


        return ResultBody.ok().data("info", info).message("信息发布成功");
    }
    private String patternTime(Date date){
        return date.getYear()+1900+"-"+date.getMonth()+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value="info", allEntries =true)
    public ResultBody deleteInfoByIds(Long[] ids) {
        try {
            infoService.removeByIds(Arrays.asList(ids));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error().message(CodeConfig.DELETE_FAIL.message);
        }
        return ResultBody.ok().data("ids",ids).message(CodeConfig.DELETE_SUCCESS.message);
    }


    /**
     * 模糊查询
     *
     * @param currentPage
     * @param pageSize
     * @param info
     * @return
     */
    @RequestMapping("/getAllInfo/{currentPage}/{pageSize}")
    @Cacheable("info")
    public ResultBody getClazz(@PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize, Info info,String account) {
        //分页信息封装Page对象
        Page<Info> page = new Page<>(currentPage, pageSize);
        //进行查询
        IPage<Info> infoList = infoService.InfoList(page, info,account);
        if (infoList.getTotal() > 0) {
            //封装Result返回
            return ResultBody.ok().data("infoList", infoList).message(CodeConfig.QUERY_SUCCESS.message);
        }
        return ResultBody.error().message(CodeConfig.QUERY_FAIL.message);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable("info")
    public ResultBody getInfoById(@PathVariable("id") Integer id) {

        Info info = infoService.getById(id);
        if (info != null) {
            return ResultBody.ok().data("info", info).message(CodeConfig.QUERY_SUCCESS.message);
        }
        return ResultBody.error().message(CodeConfig.QUERY_FAIL.message);
    }

}
